// 搜索相关的请求

import { ApiRes } from '@/types/data'
import { RootAction, RootThunkAction } from '@/types/store'
import { setHistory } from '@/utils/history'
import http from '@/utils/request'

export function getSuggestion(val: string): RootThunkAction {
  return async (dispatch) => {
    if (!val.trim()) return

    const res = await http.get<ApiRes<{ options: string[] }>>('/suggestion', {
      params: {
        q: val,
      },
    })

    // console.log(res.data.data.options) 搜索建议

    dispatch({
      type: 'search/set_suggestion',
      payload: res.data.data.options,
    } as RootAction)
  }
}

export function handleHistory(val: string): RootThunkAction {
  return async (dispatch, getState) => {
    // ... 存本地 存仓库
    //  获取之前的搜索历史 累加
    let history = getState().search.history

    // 1.去重
    history = history.filter((item) => item !== val)

    history = [val, ...history]

    // 2.检查数组长度
    if (history.length > 10) {
      history.pop()
    }

    dispatch({
      type: 'search/set_history',
      payload: history,
    } as RootAction)

    setHistory(history)
  }
}
